<?php


namespace app\astrologer\controller;


use app\common\lib\AliOss;
use app\common\lib\Util;
use OSS\Core\OssException;
use think\Cache;
use think\Env;
use think\Log;
use think\response\Json;

class Upload extends AstrAuth
{
    protected $pathType = [
        1 => 'upload/avatar', // 头像
        2 => 'upload/general',    // 一般上传
        3 => 'upload/check/left', // 认证 身份证正面
        4 => 'upload/check/right', // 认证 身份证
        5 => 'upload/check/pic', // 手持身份证
        6 => 'upload/invoice', // 发票上传
    ];

    /**
     * 文件上传大小
     * @var int
     */
    protected $file_max_size = 10485760 * 2; // 1024*1024*10=10485760  20M
    // protected $file_max_size = 314572; // 1024*1024*5=5242880  0.3M

    /**
     * 图片上传
     * @return Json
     */
    public function upload(): Json
    {
        $type = input('type/d', 0);

        $path = $this->pathType[$type] ?? '';

        $private_url = '';//隐私地址，只有 3、4、5才赋值
        $data = '';//识别的数据
        if (!$path)
        {
            return show(config('code.error'), '上传类型异常');
        }

        $file = request()->file('file');

        if (isset($file))
        {
            $config = ['size' => $this->file_max_size, 'ext' => 'jpg,png,jpeg,mp3,wav,mp4,m4a,pdf,mov,3gp,aac,amr'];
            // tp5 文件上传验证
            $info = $file->validate($config)->oss($path);
            if (!$info)
            {
                return show(10034, $file->getError());
            }
            // 获取文件名
            $filename = $info->get_filename();
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());

            try
            {
                $aliOss = AliOss::getInstance();
                $aliOss->ossUpload($filename, $content);
                if (in_array($type, [3, 4, 5, 6], true))
                {   // 设置文件私有化
                    $aliOss->setFileAuthPri($filename);
                    $private_url = $aliOss->getAuth($filename);
                    if (in_array($type, [3, 4, 5], true))
                    {
                        // 图片压缩开始---------
                        $image = \think\Image::open($file);
                        $image->thumb(800, 800)->save($file->get_tmpname());
                        $img_base64 = base64_encode(file_get_contents($file->get_tmpname()));
                        // 图片压缩结束---------
                        $msg_err = '';
                        $params = '';
                        switch ($type)
                        {
                            case 3:
                                $msg_err = '身份证正面图片';
                                $params = 'front';
                                break;
                            case 4:
                                $msg_err = '身份证反面图片';
                                $params = 'back';
                                break;
                            case 5:
                                $msg_err = '手持身份证图片';
                                break;

                        }

                        if ($img_base64)
                        {
                            if (in_array($type, [3, 4], true))
                            {//调用识别身份证的阿里云市场接口
                                $data = Util::checkIdCardPic($img_base64, $params);
                                if (3 === $type && $data['status'] === true)
                                {//身份证正面照片，把用户的头像返回去
                                    if (isset($data['data']['name'], $data['data']['nation'], $data['data']['address'], $data['data']['idcard']))
                                    {
                                        $month = date('m', strtotime($data['data']['birthday']));//19900906
                                        $day = date('d', strtotime($data['data']['birthday']));//19900906
                                        $sign_index = Util::getSignIndex($month, $day);
                                        $avatar = Env::get('host.photo') . '/zhunle_astrologer/avatar/' . $sign_index . '.png';
                                        $data['avatar'] = $avatar;
                                    } else
                                    {
                                        $data['status'] = false;
                                    }
                                } else if (4 === $type && $data['status'] === true)
                                {
                                    if (isset($data['data']['jiguan']))
                                    {
                                        $end_data = '';
                                        //检查身份证反面实效性
                                        if (isset($data['data']['end_date']))
                                        {
                                            $end_data = $data['data']['end_date'];
                                        } else if (isset($data['data']['sxrq']))
                                        {
                                            $end_data = $data['data']['sxrq'];
                                        }
                                        if ($end_data && $end_data !== '长期')
                                        {
                                            $end_date_timestamp = strtotime($end_data);
                                            if ($end_date_timestamp < time())
                                            {
                                                return show(config('code.error'), '身份证已超出有效期，请重新上传！');
                                            }
                                        }
                                    } else
                                    {
                                        $data['status'] = false;
                                    }
                                }
                            } else
                            {//调用识别手持身份证的阿里云市场接口
                                $data = Util::checkIdCardHandPic($img_base64);
                            }
                        } else
                        {
                            Log::write('上传图片：' . $msg_err . '转换base64失败', 'error', true);
                        }
                    }

                    $private_url = str_replace("http://zhunle.oss-cn-beijing.aliyuncs.com/", Env::get('host.photo'), $private_url);
                }
            }
            catch (OssException $e)
            {
                return show(10034, $e->getMessage());
            }
        } else
        {
            return show(10033, 'File is not exited.');
        }

        $msg = '上传成功';
        if (in_array($type, [3, 4, 5], true))
        {   // 文件地址缓存
            if ($data['status'] === false)
            {
                switch ($type)
                {
                    case 3:
                        $msg = isset($data['msg']) ? $data['msg'] : '身份证正面照片识别失败，请重新上传！';
                        break;
                    case 4:
                        $msg = isset($data['msg']) ? $data['msg'] : '身份证反面照片识别失败，请重新上传！';
                        break;
                    case 5:
                        $msg = isset($data['msg']) ? $data['msg'] : '手持身份证正面照片识别失败，请重新上传！';
                        break;

                }
                return show(config('code.error'), $msg);
            }

            $key = [
                3 => 'left_pic',
                4 => 'right_pic',
                5 => 'hand_idcard_pic',
            ];
            $uploadPath = Cache::get('astr_admin:upload_path:' . $this->astrInfo['id'], []);
            $uploadPath[$key[$type]] = [
                'path' => '/' . $filename,
                'data' => $data['data'],
            ];
            Cache::set('astr_admin:upload_path:' . $this->astrInfo['id'], $uploadPath, 7200); // 2小时
        }

        if (isset($data['data']['photo']))
        {
            unset($data['data']['photo']);
        }

        if ($type === 6)
        {
            $private_url = Env::get('host.domain') . '/web/agreement/astrologer_app_invoice_view.html?pdf_url=' . base64_encode($private_url);
        }
        return show(config('code.success'), $msg, [
            'path' => '/' . $filename,
            'type' => $type,
            'private_url' => $private_url,
            'data' => $data ?? '',
        ]);
    }


    /**
     * 获取oss私有图片地址，注意：$path 是以 “/” 开头的
     * @param string $path
     * @return mixed|string
     */
    public static function getOssPrivateUrl($path = '')
    {
        if ($path)
        {
            //获取私有图片地址
            $aliOss = AliOss::getInstance();
            $private_url = $aliOss->getAuth(substr($path, 1));
            return str_replace("http://zhunle.oss-cn-beijing.aliyuncs.com/", Env::get('host.photo'), $private_url);

        }
        return $path;
    }
}
